package cn.tedu._05weibo.controller;

import cn.tedu._05weibo.mapper.UserMapper;
import cn.tedu._05weibo.pojo.dto.UserLogDTO;
import cn.tedu._05weibo.pojo.dto.UserRegDTO;
import cn.tedu._05weibo.pojo.entity.User;
import cn.tedu._05weibo.pojo.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
//slf4f注解，Lombok的日志注解，用于打印日志
@Slf4j
@RestController
@RequestMapping("/v1/users/")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @PostMapping("reg")
    public int reg(@RequestBody UserRegDTO userRegDTO)
    {
        /*
            1.接收客户端传递的数据;
            2.校验数据的合法性[暂时不校验];
            3.校验用户名是否被占用[SELECT接口];
              3.1 被占用,return 2;
              3.2 未被占用,插入数据[INSERT接口], return 1;
         */
        log.debug("userRegDTO="+userRegDTO);
        System.out.println("userRegDTO = " + userRegDTO);
        UserVO userVO = userMapper.selectByUsername(userRegDTO.getUsername());
        if (userVO != null)
        {return 2;}
        User user = new User();
        BeanUtils.copyProperties(userRegDTO,user);
        user.setCreated(new Date());
        userMapper.insertUser(user);
        return 1;
    }
    @PostMapping("login")//                    spring mvc支持使用HttpSession session参数
    public int login(@RequestBody UserLogDTO userLogDTO, HttpSession session){

        System.out.println("userLogDTO = " + userLogDTO);
        UserVO userVO = userMapper.selectByUsername(userLogDTO.getUsername());
        if (userVO==null)
            return 3;
        else if(userVO.getPassword().equals(userLogDTO.getPassword())){
            session.setAttribute("user",userVO);
            return 1;
        }
        return 2;
    }
    @GetMapping("currentUser")
    public UserVO currentUser(HttpSession session){
        UserVO userVO= (UserVO) session.getAttribute("user");
        return userVO;
    }
    @GetMapping("logout")
    public void logout(HttpSession session){
        //在服务器内存中删除会话对象
        session.removeAttribute("user");
    }



}
